use crate::errors::MyError;
use base64::encode;
use lazy_static::lazy_static;
use ril::prelude::*;

const IMG_WIDTH: u32 = 120;
const IMG_HEIGHT: u32 = 50;
const TEXT_START_X: u32 = 5;
const TEXT_START_Y: u32 = 5;
const TEXT_SIZE: f32 = 36.0;
static IMG_BG: &Rgb = &Rgb::white();

lazy_static! {
    static ref FONT: Font = Font::open(dotenv!("font_file"), 20.0,).expect("打开字体文件失败");
}

pub fn gen_code_img(code: &str) -> Result<String, MyError> {
    let mut image = Image::new(IMG_WIDTH, IMG_HEIGHT, *IMG_BG);

    let text = TextSegment::new(&FONT, code, Rgb::black())
        .with_position(TEXT_START_X, TEXT_START_Y)
        .with_size(TEXT_SIZE);

    image.draw(&text);

    let mut buffer = Vec::new();
    image
        .encode(ImageFormat::Png, &mut buffer)
        .map_err(|err| MyError::Msg(format!("gen_img_code错误:{}", err)))?;

    // 将图片文件序列化为base64字符串
    let base64_str = encode(&buffer);

    // println!("base64:{}", base64_str);
    // 网页端测试<img src=""/>
    Ok(base64_str.to_owned())
}
